package org.qydjk.common.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;


public class HttpUtil {
	private static final Log logger=LogFactory.getLog(HttpUtil.class);
	public static RequestConfig getConfig(){
		return  RequestConfig.custom()
				.setConnectTimeout(30*1000)
				.setSocketTimeout(60*1000)
				.build();//设置连接和响应超时时间
	}
	
	public static String post(String url,Map<String, Object> params) throws Exception{
		return post(url, params, null, null);
	}
	
	public static String post2(String url,Map<String,String> params) throws Exception{
		return post2(url, params, null, null);
	}
	
	public static String post(String url,String entityContent,String charset) throws Exception{
		String responseContent = null;
		if(StringUtil.isEmptyOrNull(charset)){
			charset="utf-8";
		}
		HttpClient httpClient = HttpClients.createDefault();
		HttpPost post = new HttpPost(url);
		post.setConfig(getConfig());
		
		post.setEntity(new StringEntity(entityContent, charset));
		
		HttpResponse response = httpClient.execute(post);
		
		HttpEntity entity = response.getEntity();
		if (entity != null) {
			responseContent = EntityUtils.toString(entity, charset);
			EntityUtils.consume(entity);
		}
			
		return responseContent;
	}
	
	
	public static String post2(String url,Map<String, String> params, String paramsEncodeCharset,Map<String, String> headers)
			throws Exception{
		String responseContent = null;
		HttpClient httpClient = HttpClients.createDefault();
		if(StringUtil.isEmptyOrNull(paramsEncodeCharset)){
			paramsEncodeCharset="utf-8";
		}
		HttpPost post = new HttpPost(url);
		post.setConfig(getConfig());
		
		List<NameValuePair> list=new ArrayList<NameValuePair>();
		for(Entry<String, String> entity:params.entrySet()){
			NameValuePair pair=new BasicNameValuePair(entity.getKey(), entity.getValue());
			list.add(pair);
		}
		
         post.setEntity(new UrlEncodedFormEntity(list, paramsEncodeCharset)); 
		if(headers!=null && headers.size()>0){
			for(Entry<String,String> entry:headers.entrySet()){
				String key=entry.getKey();
				String value=entry.getValue();
				post.addHeader(key, value);
				System.out.println(key+":"+value);
				
			}
		}
		
		HttpResponse response = httpClient.execute(post);
		
		HttpEntity entity = response.getEntity();
		if (entity != null) {
			responseContent = EntityUtils.toString(entity, "utf-8");
			EntityUtils.consume(entity);
		}
			
		return responseContent;
	}
	
	
	public static String post(String url,Map<String, Object> params, String paramsEncodeCharset,Map<String, String> headers)
			throws Exception{
		String responseContent = null;
		HttpClient httpClient = HttpClients.createDefault();
		if(StringUtil.isEmptyOrNull(paramsEncodeCharset)){
			paramsEncodeCharset="utf-8";
		}
		HttpPost post = new HttpPost(url);
		post.setConfig(getConfig());
		 //请求实体(实体中保存post请求的参数,包括文件)
        MultipartEntityBuilder builder=MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
         if(params!=null && params.size()>0){
             for(Entry<String,Object> entry : params.entrySet()){
                String key=entry.getKey();
                Object value=entry.getValue();
                if(value instanceof String){
             	   builder.addTextBody(key, (String)value, ContentType.TEXT_PLAIN.withCharset("utf-8"));
                }else if(value instanceof File){
             	   builder.addBinaryBody(key, (File) value, ContentType.APPLICATION_OCTET_STREAM, URLEncoder.encode(((File) value).getName(),"utf-8"));
                }
                
             } 
            post.setEntity(builder.build()); 
         }
         
		System.out.println("post request header:");
		if(headers!=null && headers.size()>0){
			for(Entry<String,String> entry:headers.entrySet()){
				String key=entry.getKey();
				String value=entry.getValue();
				post.addHeader(key, value);
				System.out.println(key+":"+value);
				
			}
		}
		
		HttpResponse response = httpClient.execute(post);
		
		HttpEntity entity = response.getEntity();
		if (entity != null) {
			responseContent = EntityUtils.toString(entity, "utf-8");
			EntityUtils.consume(entity);
		}
			
		return responseContent;
	}
	
	
	public static String get(String url) throws Exception{
		return get(url,null);
	}
	
	public static String get(String url,Map<String,String> headers) throws Exception{
		long responseLength = 0;                         //响应长度 
        String responseContent = null;                   //响应内容 
        HttpClient httpClient = HttpClients.createDefault(); //创建默认的httpClient实例 
        
    	
    	HttpGet get=new HttpGet(url);
    	get.setConfig(getConfig());
    	if(headers!=null && headers.size()>0){
    		for(Entry<String,String> entry:headers.entrySet()){
    			String key=entry.getKey();
    			String value=entry.getValue();
    			get.addHeader(key, value);
    		}
    	}
    	
    	HttpResponse resp=httpClient.execute(get);
    	HttpEntity entity=resp.getEntity();
    	if (entity!=null) { 
            responseLength = entity.getContentLength(); 
            responseContent = EntityUtils.toString(entity,"utf-8"); 
            EntityUtils.consume(entity); 
        } 
    	 logger.debug("请求地址: " + get.getURI()); 
         logger.debug("响应状态: " + resp.getStatusLine()); 
         logger.debug("响应长度: " + responseLength); 
         logger.debug("响应内容: " + responseContent); 
    	return responseContent;
	}
	

	public static String getIp(HttpServletRequest request){
		 String ip = request.getHeader("X-Forwarded-For");
		 if(StringUtil.isEmptyOrNull(ip) || "unknown".equalsIgnoreCase(ip)){
			 ip=request.getHeader("X-Real-IP");
			 if(StringUtil.isEmptyOrNull(ip) || "unknown".equalsIgnoreCase(ip)){
				 ip=request.getRemoteAddr();
			 }
		 }
	     return ip;
	}
	
	public static void main(String[] args) {
		try {
			Map<String,Object> params=new HashMap<String, Object>();
			params.put("userId", "111");
			params.put("file", new File("C:/Users/Administrator/Desktop/附3最高人民法院民事案件案由规定.doc"));
			System.out.println(post("http://file.lawerwin.com/upload.do", params));;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	
}
